# config/system_config.py
"""
系统配置文件 - 配置翁法洛斯平台的混合AI架构
包含在线/离线模型配置、上下文管理配置等
"""

from typing import Dict, List, Optional, Any
from dataclasses import dataclass
from enum import Enum
import os

class ModelArchitecture(Enum):
    """模型架构类型"""
    LOCAL_ONLY = "local_only"           # 仅本地模型
    ONLINE_ONLY = "online_only"         # 仅在线模型
    HYBRID = "hybrid"                   # 混合架构（推荐）

class SystemMode(Enum):
    """系统运行模式"""
    DEVELOPMENT = "development"
    PRODUCTION = "production"
    TESTING = "testing"

@dataclass
class ModelConfig:
    """模型配置"""
    # 本地模型配置
    local_model_enabled: bool = True
    local_model_path: str = "models/checkpoints/"
    local_model_type: str = "ppo"  # ppo, dqn, a2c等
    
    # 在线模型配置
    online_model_enabled: bool = True
    online_model_provider: str = "openai"  # openai, anthropic, azure等
    online_model_name: str = "gpt-3.5-turbo"
    online_api_key: Optional[str] = None
    online_base_url: Optional[str] = None
    
    # 模型切换策略
    complexity_threshold: float = 0.7  # 复杂度阈值，超过此值使用在线模型
    fallback_enabled: bool = True      # 是否启用故障转移
    timeout_seconds: int = 30          # 模型调用超时时间

@dataclass
class ContextConfig:
    """上下文管理配置"""
    # 上下文存储配置
    context_db_path: str = "data/onpharos_context.db"
    context_ttl_minutes: int = 1440    # 上下文默认生存时间（24小时）
    
    # 上下文管理策略
    max_contexts_per_component: int = 1000
    context_cleanup_interval: int = 3600  # 上下文清理间隔（秒）
    
    # 上下文优先级配置
    high_priority_ttl: int = 4320       # 高优先级上下文生存时间（3天）
    medium_priority_ttl: int = 1440     # 中优先级上下文生存时间（1天）
    low_priority_ttl: int = 120         # 低优先级上下文生存时间（2小时）

@dataclass
class NetworkConfig:
    """网络配置"""
    # 网络监控配置
    network_monitor_enabled: bool = True
    check_interval: int = 30            # 网络状态检查间隔（秒）
    timeout: float = 10.0               # 请求超时时间（秒）
    latency_threshold: float = 2000.0   # 延迟阈值（毫秒）
    
    # 故障转移配置
    failover_enabled: bool = True
    retry_attempts: int = 3             # 重试次数
    retry_delay: float = 1.0            # 重试延迟（秒）

@dataclass
class ComponentStrategyConfig:
    """组件策略配置"""
    # 管理员组件（使用在线模型）
    admin_components: List[str] = None
    # 智能体组件（使用本地模型）
    agent_components: List[str] = None
    
    def __post_init__(self):
        if self.admin_components is None:
            self.admin_components = [
                "training_controller",
                "admin_system", 
                "system_optimizer",
                "decision_maker",
                "strategy_planner"
            ]
        if self.agent_components is None:
            self.agent_components = [
                "mydei_agent",
                "hyacine_agent",
                "tribbie_agent",
                "aglaea_agent",
                "anaxa_agent",
                "castorice_agent",
                "cerydra_agent",
                "cipher_agent",
                "evernight_agent",
                "hyacine_agent",
                "hysilens_agent",
                "phainon_agent",
                "terrae_agent",
                "lygus_agent",
                "irontomb_agent"
            ]

class SystemConfig:
    """系统配置主类"""
    
    def __init__(self, mode: SystemMode = SystemMode.DEVELOPMENT):
        self.mode = mode
        self.architecture = ModelArchitecture.HYBRID
        
        # 从环境变量加载敏感配置
        self.model_config = ModelConfig(
            online_api_key=os.getenv("ONLINE_MODEL_API_KEY"),
            online_base_url=os.getenv("ONLINE_MODEL_BASE_URL")
        )
        self.context_config = ContextConfig()
        self.network_config = NetworkConfig()
        self.component_strategy_config = ComponentStrategyConfig()
        
        # 根据运行模式调整配置
        self._configure_for_mode()
    
    def _configure_for_mode(self):
        """根据运行模式调整配置"""
        if self.mode == SystemMode.DEVELOPMENT:
            # 开发模式配置
            self.model_config.timeout_seconds = 60
            self.context_config.context_ttl_minutes = 60 # 缩短上下文生存时间
            self.network_config.check_interval = 60
        elif self.mode == SystemMode.PRODUCTION:
            # 生产模式配置
            self.model_config.timeout_seconds = 30
            self.network_config.check_interval = 30
            self.context_config.context_cleanup_interval = 1800
        elif self.mode == SystemMode.TESTING:
            # 测试模式配置
            self.model_config.online_model_enabled = False
            self.model_config.fallback_enabled = False
            self.network_config.network_monitor_enabled = False
    
    def get_component_model_type(self, component_name: str) -> str:
        """获取组件的模型类型"""
        if component_name.lower() in self.component_strategy_config.admin_components:
            return "online" if self.model_config.online_model_enabled else "local"
        elif component_name.lower() in self.component_strategy_config.agent_components:
            return "local"
        else:
            # 默认策略：根据复杂度决定
            return "hybrid"
    
    def to_dict(self) -> Dict[str, Any]:
        """转换为字典格式"""
        return {
            "mode": self.mode.value,
            "architecture": self.architecture.value,
            "model_config": {
                "local_model_enabled": self.model_config.local_model_enabled,
                "local_model_type": self.model_config.local_model_type,
                "online_model_enabled": self.model_config.online_model_enabled,
                "online_model_provider": self.model_config.online_model_provider,
                "online_model_name": self.model_config.online_model_name,
                "online_api_key_set": self.model_config.online_api_key is not None,
                "complexity_threshold": self.model_config.complexity_threshold,
                "fallback_enabled": self.model_config.fallback_enabled,
                "timeout_seconds": self.model_config.timeout_seconds
            },
            "context_config": {
                "context_db_path": self.context_config.context_db_path,
                "context_ttl_minutes": self.context_config.context_ttl_minutes,
                "max_contexts_per_component": self.context_config.max_contexts_per_component,
                "context_cleanup_interval": self.context_config.context_cleanup_interval
            },
            "network_config": {
                "network_monitor_enabled": self.network_config.network_monitor_enabled,
                "check_interval": self.network_config.check_interval,
                "timeout": self.network_config.timeout,
                "latency_threshold": self.network_config.latency_threshold,
                "failover_enabled": self.network_config.failover_enabled,
                "retry_attempts": self.network_config.retry_attempts
            },
            "components": {
                "admin_components": self.component_strategy_config.admin_components,
                "agent_components": self.component_strategy_config.agent_components
            }
        }
    
    def save_to_file(self, filepath: str):
        """保存配置到文件"""
        import json
        with open(filepath, 'w', encoding='utf-8') as f:
            json.dump(self.to_dict(), f, indent=2, ensure_ascii=False)
    
    @classmethod
    def load_from_file(cls, filepath: str) -> 'SystemConfig':
        """从文件加载配置"""
        import json
        with open(filepath, 'r', encoding='utf-8') as f:
            data = json.load(f)
        
        # 创建新的配置实例
        config = cls(SystemMode(data.get('mode', 'development')))
        
        # 更新配置值
        if 'architecture' in data:
            config.architecture = ModelArchitecture(data['architecture'])
        
        # 这里可以进一步更新其他配置值...
        
        return config

# 默认配置实例
def get_default_config(mode: SystemMode = None) -> SystemConfig:
    """获取默认系统配置"""
    if mode is None:
        mode = SystemMode(os.getenv("SYSTEM_MODE", "development"))
    return SystemConfig(mode)

# 环境特定配置
def get_config_for_environment(env_name: str) -> SystemConfig:
    """获取特定环境的配置"""
    mode_map = {
        'dev': SystemMode.DEVELOPMENT,
        'development': SystemMode.DEVELOPMENT,
        'prod': SystemMode.PRODUCTION, 
        'production': SystemMode.PRODUCTION,
        'test': SystemMode.TESTING,
        'testing': SystemMode.TESTING
    }
    
    mode = mode_map.get(env_name.lower(), SystemMode.DEVELOPMENT)
    return SystemConfig(mode)

# 使用示例
if __name__ == "__main__":
    # 创建开发环境配置
    dev_config = get_config_for_environment("development")
    print("开发环境配置:")
    print(f"架构: {dev_config.architecture.value}")
    print(f"模型配置: 在线={dev_config.model_config.online_model_enabled}, 本地={dev_config.model_config.local_model_enabled}")
    
    # 创建生产环境配置
    prod_config = get_config_for_environment("production")
    print("\n生产环境配置:")
    print(f"架构: {prod_config.architecture.value}")
    
    # 检查特定组件的模型类型
    print(f"\ntraining_controller 使用模型类型: {prod_config.get_component_model_type('training_controller')}")
    print(f"mydei_agent 使用模型类型: {prod_config.get_component_model_type('mydei_agent')}")
